<?php

declare(strict_types=1);


namespace app\result;


use app\model\admin\Admin;
use app\model\Setting;
use app\model\UpdateLog;
use think\Exception;
use think\facade\App;
use think\facade\Db;
use think\helper\Arr;

class SettingResult extends BaseResult
{
    public function list(array $args)
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['title|description', 'like', '%' . trim($args['keyword']) . '%'];
        }
        $model = new Setting();
        $total = $model->data_count($where);
        $data = $model->data_list($where, 'id,key_name,title,description,type,updated_at', 'id desc', $page, $pageSize);
        if ($data) {
            foreach ($data as &$v) {
                $v['type_desc'] = $v['type'] == 1 ? 'json' : ($v['type'] == 2 ? '富文本' : '简单字符串');
            }
            unset($v);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }


    /**
     * 获取配置，一次性获取多个配置项时，使用逗号拼接
     * @param string $keyName
     * @param bool $returnApi 是否返回Api格式
     * @return array
     * @return array
     */
    public function get(string $keyName, bool $returnApi = false): array
    {
        $settingModel = new Setting();
        if (empty($keyName)) {
            return [];
        }
        $key_name = explode(',', $keyName);
        $list = $settingModel->data_list_nopage(compact('key_name'), ['key_name', 'title', 'value', 'description', 'type'], '');
        if (count($key_name) === 1) {
            $list = current($list);
        }
        $list = $list ?: [];
        return $returnApi ? self::success_return('success', $list) : $list;
    }


    public function info($id): array
    {
        $settingModel = new Setting();
        $data = $settingModel->data_get(['id' => $id]);
        if (!$data) {
            return self::error_return("配置项不存在");
        }
        $data['value'] = htmlspecialchars_decode($data['value']);
        return self::success_return('success', $data);
    }

    public function delete($id)
    {
        $model = new Setting();
        $setting = $model->data_get(['id' => $id]);
        if (!$setting) {
            return self::error_return("配置项不存在");
        }
        $model->data_del(['id' => $id]);
        return self::success_return('删除成功');
    }

    public function action($args): array
    {
        $rules = [
            ['type', 'number|in_array:1,2,3', '类型必传|类型错误'],
            ['key_name', 'empty|max:50', '配置key不能为空|配置key长度不能大于50'],
            ['title', 'empty|max:50', '配置项名称不能为空|配置项名称长度不能大于50'],
            ['value', 'empty', '配置项的值必传'],
        ];
        $check = check_param($args, $rules);
        if ($check['status'] != 0) {
            return self::error_return($check['msg']);
        }
        $key_name = $args['key_name'];
        //仅支持字母开头，数字，下划线，中划线
        if (!preg_match('/^[a-zA-Z][a-zA-Z0-9_-]{0,49}$/', $key_name)) {
            return self::error_return("标识仅支持字母开头，数字，下划线，中划线");
        }

        $model = new Setting();
        $id = intval($args['id'] ?? 0);
        if ($id) {
            $setting = $model->data_get(['id' => $id]);
            if (!$setting) {
                return self::error_return("配置项不存在");
            }
        }
        $hasKey = $model->data_get(['key_name' => $args['key_name']]);
        if ($hasKey) {
            if (!$id) {
                return self::error_return("配置项标识已存在");
            }
            if ($setting['id'] !== $id) {
                return self::error_return("配置项标识已存在");
            }
        }
        $baseData = [
            'key_name' => $args['key_name'],
            'title' => $args['title'],
            'description' => $args['description'] ?? '',
            'type' => $args['type'],
            'value' => $args['value'],
        ];
        if ($id) {
            $res = $model->data_update(['id' => $id], $baseData);
        } else {
            $res = $model->data_add($baseData);
        }
        return self::success_return('success', $res);
    }


    public function menu_list()
    {
        // 获取菜单，tp6后面的版本主持子目录config设置，不打算放在config里面（会每次都引入）
        $file = App::getAppPath() . '/controller/admin/config/client_menu.php';
        if (!file_exists($file)) {
            $data = [];
        } else {
            $data = include $file;
        }
        return self::success_return('success', [
            'list' => $data,
        ]);
    }

    public function admin_info($admin_id)
    {
        $data = (new Admin())->data_get(['admin_id' => $admin_id], ['admin_id', 'username']);

        return self::success_return('success', $data);
    }

    //修改管理密码
    public function change_password($admin_id, $pwd, $pwd1)
    {
        if (empty($pwd)) {
            return self::error_return('新密码不能为空');
        }
        $admin = (new Admin())->data_get(['admin_id' => $admin_id], ['admin_id', 'password']);
        if (!$admin) {
            return self::error_return('管理员不存在');
        }
        if (trim($pwd) !== $pwd1) {
            return self::error_return('两次输入的密码不一致');
        }
        //10位随机数
        $salt = substr(md5(uniqid()), 0, 10);
        $pwd = md5($pwd . $salt);
        $up = [
            'password' => $pwd,
            'salt' => $salt,
        ];
        (new Admin())->data_update(['admin_id' => $admin_id], $up);
        return self::success_return('修改成功');
    }

    /**
     * 获取app信息
     * @return array
     */
    public function base_info($args = [])
    {
        $data = [
            'beian_no' => config('domain.beian.app'),
            'beian_no_xcx' => config('domain.beian.xcx'),
            'beian_url' => config('domain.beian.url'),
        ];
        return self::success_return('success', $data);
    }
}
